import { MODEL_chat_list } from './constants';
import { getFromModel, saveToModel } from './util';

// 精确小数点后位数
export function formatNum(num, precision = 3) {
	if (typeof num !== 'number') return 0;

	const multiple = 10 ** precision;

	// 精确到精度位
	num = Math.round(num * multiple) / multiple;

	// 去除末尾的无效数字0
	num = Number(num);

	return num;
}

//获取消息通知未读数量
export function getBarNumber(chatList) {
	chatList = chatList || getFromModel(MODEL_chat_list) || [];
	let sum = 0;
	chatList.map((item) => {
		if (item.unread) {
			sum += Number(item.unread);
		}
	});
	return sum;
}

//一键已读
export function removeBarNumber() {
	let chatList = getFromModel(MODEL_chat_list) || [];
	let sum = 0;
	chatList.map((item) => {
		if (item.unread) {
			item.unread = null;
		}
	});
	saveToModel(MODEL_chat_list, chatList);
	setBarNumber();
}

//设置消息通知未读数量
export function setBarNumber() {
	let chatList = getFromModel(MODEL_chat_list) || [];
	const barNumber = getBarNumber(chatList);
	const isShow = (barNumber > 0);
	if (isShow) {
		wx.setTabBarBadge({
			index: 2,
			text: String(barNumber),
		});
	} else {
		wx.removeTabBarBadge({ index: 2 });
	}

}

export function makePhone() {
	wx.makePhoneCall({
		phoneNumber: '0571-87808591'
	})
}

export function getUserProfile(cb) {
	wx.getUserProfile({
		lang: 'zh_CN',
		desc: '用于完善会员资料',
		success: res => {
			cb(null, res.userInfo)
		},
		fail: e => {
			cb(e)
		}
	})
}